package com.meichis.yndms.component;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;

import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.ScreenUtil;
import com.meichis.mcsappframework.wheel.WheelView;
import com.meichis.mcsappframework.wheel.adapters.ArrayWheelAdapter;
import com.meichis.yndms.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenhaifei on 2016/8/11.
 */
public class ChoicePopView<T> extends PopupWindow implements View.OnClickListener {
    private Context mContext;
    private SelectedListener mListener;
    private WheelView wv_choice;

    private List<T> mDatas;
    private String dTextData;
    private boolean isCyclic = false;

    public interface SelectedListener {
        void choice(int position);
    }

    public ChoicePopView(Context context, List<T> items, String dTextData, SelectedListener listener) {
        this(context, items, dTextData, items == null ? 0 : items.size() / 2, listener);
    }

    public ChoicePopView(Context context, List<T> items, String dTextData, int position, SelectedListener listener) {
        super();

        mContext = context;
        mListener = listener;
        mDatas = items;
        this.dTextData = dTextData;

        initViews(context);
        wv_choice.setCurrentItem(position);
        setWidth(ScreenUtil.getScreenWidth());//设置popwindow的宽为屏幕的实际像素宽
        setHeight(ScreenUtil.dip2px(240));
        setFocusable(true);
        setBackgroundDrawable(new BitmapDrawable());
        setOutsideTouchable(true);
        setAnimationStyle(R.style.AnimBottom);
    }

    private void initViews(Context context) {
        View contentView = LayoutInflater.from(context).inflate(R.layout.layout_choice_popview, null);
        setContentView(contentView);
        contentView.findViewById(R.id.bt_ok).setOnClickListener(this);
        wv_choice = (WheelView) contentView.findViewById(R.id.wv_choice);
        wv_choice.setVisibleItems(5);
        wv_choice.setCyclic(isCyclic);
        setAdapter();
    }

    private void setAdapter() {
        if (mDatas == null)
            return;
        ArrayWheelAdapter adapter = new ArrayWheelAdapter<>(mContext, (ArrayList) mDatas, dTextData);
        adapter.setTextSize(16);
        wv_choice.setViewAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        this.dismiss();
        switch (v.getId()) {
            case R.id.bt_ok:
                mListener.choice(wv_choice.getCurrentItem());
                break;
        }
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        if (mDatas == null || mDatas.size() == 0) {
            MessageTools.showLongToast("没有数据！");
            this.dismiss();
        }
    }
}
